package org.NooLab.demoinstances;



 
import org.NooLab.itexx.ITexxFactory;
import org.NooLab.itexx.co.CoWorkerIntf;
import org.NooLab.utilities.logging.LogControl;

 

import processing.core.*;

/*
 * 
 * better: starting as app and opening a secondary window
 * 
 */


/**
 * 
 * note that the iTexxFactory will check the start requests such that it will be started
 * only once.
 * 
 * 
 * TODO: option "-clean", which issues stop files for all known applications 2 times, 
 *       before creating the processes
 *       
 *       restart of all the processes (similar to the clean start), also by indicator file
 *       "restart.all"  restart.[process name] -> iTexxFactory needs its own file watching process 
 * 
 * 
 */
public class X1_iTexx_Applet  extends PApplet{

	
	private static final long serialVersionUID = -75401849238245009L; 
	
	
	ITexxInstanceI1 itexxInstance ;
	 
	PApplet applet;
	
	
	public void setup(){
		 
		applet = this;
		
		try{
			ITexxFactory.init(this.getClass());
		 
			
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return;
		}
		  
		showKeyCommands();
		
		draw();
	 
	}
	
	
	// ................................
	public void draw(){
		background( 238,128,128);
		
	}
	// ................................
	
	
	public void stop(){
	
		ITexxFactory.stop();
	}
	
	public void keyPressed() {

		
		
		if (key=='t'){
			
			looping = true;
			this.loop() ;
			 
			startEngines(1) ; // 1= optimizer, 0=simple som (not recommended for most tasks)
			 
		}
		 
		
		if (key=='x'){
			// somInstance. ...
			ITexxFactory.stop();
			
		}
		  
	}
	
	 

	private void showKeyCommands(){

		println();
		println("Welcome to iTexx!\n");
		println("the following key commands are available for minimalistic user-based control...");
		println();
		println("   t  ->  start the listeners and all required modules ");
		println();
		println("   c  ->  open the basic configuration file  ");
		println("   r  ->  show the 'readme' file  ");
		println();
		println("   x  ->  exit");
		println();
		println("------------------------------------------------------------------");
		println();

	}
	
	/**
	 * 
	 * @param somtype 0=default: simple, single run; 1=som optimizer
	 * @param lastProjectName2 
	 */
	private void startEngines( int somtype ){
		println();
		
		itexxInstance = new ITexxInstanceI1(  ) ;
		
		itexxInstance.startInstance() ;
	}
	
	
}

 
class ITexxInstanceI1{

	ITexxFactory itxFactory;
	
	
	public ITexxInstanceI1(){
		
		LogControl.Level = 2 ; 
	}
	
	
	public void startInstance() { 


		itxFactory = ITexxFactory.getInstance() ;

		
		if (itxFactory != null){

			ITexxFactory.init(this.getClass()) ;
		
			itxFactory.addServerPort(7209);
			itxFactory.addServerPort(CoWorkerIntf._mainServerPort); // 7210
			
			itxFactory.start() ;
			
		}
	}
	
}




